const Base = require("./base");
module.exports = class PayService extends Base {
  payProductList() {
    let sql = `SELECT a.*,b.welfare FROM pay AS a LEFT JOIN product_pay_type AS b ON a.pay_type=b.id WHERE a.status>0`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0]);
  }
  payType(isios) {
    let sql = `SELECT * FROM pay_type WHERE status=0 AND type=${isios ? 1 : 0}`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0]);
  }

  savePayLog(params) {
    const { keys, replacements, values } = this.installParams(params);
    let sql = `INSERT INTO pay_log(${keys}) VALUES(${values})`;
    return this.app.mysql.use("foindia").query(sql, {
      replacements,
    });
  }
  updatePayLog(params) {
    const { replacements, values } = this.installParams(params, 2);
    let sql = `UPDATE pay_log SET ${values} WHERE order_id='${params.order_id}'`;
    return this.app.mysql.use("foindia").query(sql, {
      replacements,
    });
  }
  getPayLog(uid) {
    // 查询出充值记录中充值成功并且用户权益存在的数据
    let sql = `SELECT * FROM pay_log WHERE uid='${uid}' AND end_time>NOW() AND status=1 ORDER BY create_time`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0]);
  }
  getLastPayLog(uid) {
    // 查询出充值记录中充值成功并且用户权益存在的数据
    let sql = `SELECT * FROM pay_log WHERE uid='${uid}' AND end_time>NOW() AND status=1 ORDER BY end_time DESC Limit 0,1`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0][0]);
  }
  getPayRecord(uid) {
    // 查询出充值记录中充值成功并且用户权益存在的数据
    let sql = `SELECT a.id,a.pro_id,a.pay_type,a.pro_name,a.order_id,a.price,a.discount,a.start_time,a.end_time,b.plus
    FROM pay_log AS a LEFT JOIN product_pay_type AS b ON a.pay_type=b.id
    WHERE uid='${uid}' AND end_time>NOW() AND a.status=1 ORDER BY a.start_time`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0]);
  }

  getShareWelfare(params) {
    // 查询出充值记录中充值成功并且用户权益存在的数据
    // 最近一月MONTH(end_time)=MONTH(CURDATE())
    // 最近1天 DATE_SUB(CURDATE(), INTERVAL 1 DAY)
    const exp = `uid='${params.uid}' AND pay_type='${params.pay_type}' AND status=1`;
    let sql = `SELECT COUNT(id) AS count FROM pay_log WHERE ${exp};SELECT * FROM pay_log WHERE ${exp} ORDER BY create_time DESC LIMIT 0,1`;
    return this.app.mysql
      .use("foindia")
      .query(sql)
      .then((res) => res[0])
      .then((res) => {
        const countObj = res[0][0];
        const latest = res[1][0];
        return {
          count: countObj ? countObj.count : 0,
          latest,
        };
      });
  }
};
